package com.sk.weichat.ui.nearby;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.adapter.SearchFriendAdapter;
import com.sk.weichat.bean.AddAttentionResult;
import com.sk.weichat.bean.AttentionUser;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.User;
import com.sk.weichat.bean.message.ChatMessage;
import com.sk.weichat.bean.message.NewFriendMessage;
import com.sk.weichat.bean.message.XmppMessage;
import com.sk.weichat.broadcast.CardcastUiUpdateUtil;
import com.sk.weichat.db.dao.ChatMessageDao;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.NewFriendDao;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.helper.FriendHelper;
import com.sk.weichat.ui.base.EasyFragment;
import com.sk.weichat.ui.me.PersonalCenterActivity;
import com.sk.weichat.util.TimeUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.SelectionFrame;
import com.sk.weichat.xmpp.ListenerManager;
import com.sk.weichat.xmpp.listener.ChatMessageListener;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.callback.ListCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ArrayResult;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import okhttp3.Call;

/**
 * 搜索陌生人列表
 * create by swy 2019-07-15
 */
public class SearchUserFragment extends EasyFragment {

    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private SearchFriendAdapter mAdapter;
    private ArrayList<User> mFriendList;
    private String mKeyWord;// 关键字(keyword)
    private int mSex;       // 城市Id(cityId)
    private int mMinAge;    // 行业Id(industryId)
    private int mMaxAge;    // 职能Id(fnId)
    private int mShowTime;  // 日期(days)
    private int mPage = 0;
    private int mPageSize = 20;
    private String mLoginUserId;


    public SearchUserFragment() {
        mFriendList = new ArrayList<>();
    }

    @Override
    protected int inflateLayoutId() {
        return R.layout.fragment_search_friend;
    }

    @Override
    protected void onActivityCreated(Bundle savedInstanceState, boolean createView) {
        initView();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    private void initView() {
        mLoginUserId = coreManager.getSelf().getUserId();
        initRecycerView();

        refreshLayout = findViewById(R.id.refresh_search_layout);
        refreshLayout.setDragRate(0.4f);//刷新拉动阻尼效果，数值越小，拉动距离越大
        refreshLayout.setEnableOverScrollBounce(false);//禁止越界回弹
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshLayout.setNoMoreData(false);
                mPage = 0;
                requestData(true,false);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPage++;
                requestData(false,false);
            }
        });
    }

    private void initRecycerView() {
        recyclerView = findViewById(R.id.recycler_search_friend);
        LinearLayoutManager manager = new LinearLayoutManager(mActivity);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);

        mAdapter = new SearchFriendAdapter(mFriendList);
        mAdapter.setHasStableIds(true);
        recyclerView.setAdapter(mAdapter);
        //禁止RecyclerView的默认动画
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);

        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent;
                switch (view.getId()) {

                    case R.id.layout_search_friend_item://点击item
                        intent = new Intent(getActivity(), PersonalCenterActivity.class);
                        intent.putExtra(AppConstant.EXTRA_USER_ID, mFriendList.get(position).getUserId());
                        startActivity(intent);
                        break;

                    case R.id.layout_search_attention_btn://关注按钮
                        AttentionUser attentionUser = mFriendList.get(position).getFriends();
                        if (attentionUser != null && (attentionUser.getStatus() == Friend.STATUS_FRIEND || attentionUser.getStatus() == Friend.STATUS_ATTENTION)) {
                            //取消关注
                            showCancelAttentionDialog(mFriendList.get(position));
                        } else {
                            //关注
                            doAddAttention(mFriendList.get(position));
                        }

                        break;

                }
            }
        });
    }

    @Override
    public void onClick(View v) {

    }

    public void setMsg(String mKeyWord, int mSex, int mMinAge, int mMaxAge, int mShowTime) {
        this.mKeyWord = mKeyWord;
        this.mSex = mSex;
        this.mMinAge = mMinAge;
        this.mMaxAge = mMaxAge;
        this.mShowTime = mShowTime;
    }

    public void requestData(final boolean isPullDwonToRefersh,boolean isShow) {
        if (isPullDwonToRefersh) {
            mPage = 0;
        }
        if (isShow){

        }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("pageIndex", String.valueOf(mPage));
        // params.put("pageSize", String.valueOf(AppConfig.PAGE_SIZE));
        params.put("pageSize", String.valueOf(mPageSize));
        if (!TextUtils.isEmpty(mKeyWord)) {
            params.put("nickname", mKeyWord);
        }
        if (mSex != 0) {
            params.put("sex", String.valueOf(mSex));
        }

        if (mMinAge != 0) {
            params.put("minAge", String.valueOf(mMinAge));
        }

        if (mMaxAge != 0) {
            params.put("maxAge", String.valueOf(mMaxAge));
        }

        params.put("active", String.valueOf(mShowTime));

        HttpUtils.get().url(coreManager.getConfig().USER_NEAR)
                .params(params)
                .build()
                .execute(new ListCallback<User>(User.class) {
                    @Override
                    public void onResponse(ArrayResult<User> result) {
                        refreshLayout.setVisibility(View.VISIBLE);
                        DialogHelper.dismissProgressDialog();
                        if (result.getData() != null) {
                            List<User> datas = result.getData();
                            if (mPage == 0) {
                                refreshLayout.finishRefresh();
                                mFriendList.clear();
                            } else if(datas.size() == mPageSize){
                                refreshLayout.finishLoadMoreWithNoMoreData();
                            }else{
                                refreshLayout.finishLoadMore();
                            }
                            if (datas.size() == 1) {
                                Intent intent = new Intent(getContext(), PersonalCenterActivity.class);
                                intent.putExtra(AppConstant.EXTRA_USER_ID, datas.get(0).getUserId());
                                startActivity(intent);
                            } else {
                                mFriendList.addAll(datas);
                                mAdapter.notifyDataSetChanged();
                            }
                            UserListGatherActivity activity = (UserListGatherActivity) getActivity();
                            activity.ll_layout_search_empty.setVisibility(View.GONE);
                        } else {
                            UserListGatherActivity activity = (UserListGatherActivity) getActivity();
                            if (mPage == 0) {
                                activity.ll_layout_search_empty.setVisibility(View.VISIBLE);
                            } else {
                                refreshLayout.finishLoadMoreWithNoMoreData();
                                refreshLayout.setEnableFooterFollowWhenNoMoreData(true);
                            }
                        }

                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        Toast.makeText(getActivity(), R.string.check_network, Toast.LENGTH_SHORT).show();
                        // TODO: 2019/7/15
                        mFriendList.clear();
                        mAdapter.notifyDataSetChanged();
                    }
                });
    }

    public void clearData() {
        mFriendList.clear();
        mAdapter.notifyDataSetChanged();
        refreshLayout.resetNoMoreData();
        refreshLayout.onStopNestedScroll(recyclerView);
    }

    // 点击加好友就调用这个方法，
    private void doAddAttention(User user) {

        if (user.getFriends() == null) {
            AttentionUser attentionUser = new AttentionUser();
            attentionUser.setStatus(Friend.STATUS_UNKNOW);
            user.setFriends(attentionUser);
        }

        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("toUserId", user.getUserId());

        DialogHelper.showDefaulteMessageProgressDialog(getActivity());

        // 首先是调接口，
        HttpUtils.get().url(coreManager.getConfig().FRIENDS_ATTENTION_ADD)
                .params(params)
                .build()
                .execute(new BaseCallback<AddAttentionResult>(AddAttentionResult.class) {

                    @Override
                    public void onResponse(ObjectResult<AddAttentionResult> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1 && result.getData() != null) {

                            FriendHelper.updateFriendRelationship(mLoginUserId, user);
                            // Friend friend = FriendDao.getInstance().getFriend(mLoginUserId, user.getUserId());
                            if (result.getData().getType() == 1 || result.getData().getType() == 3) {
                                // 需要验证就发送打招呼的消息，
                                if (user.getFriends() == null
                                        || (user.getFriends().getReplyStatus() != Friend.STATUS_REPLAY_BOTH
                                        && user.getFriends().getIsBeenBlack() != 1
                                        && result.getData().getIsFollowed() == 0)) {// 未回复并且未关注过的发送打招呼消息

                                    doSayHello(user, coreManager.getSelf().getNickName() + "关注了你");
                                }
                                if (user.getFriends().getIsBeenBlack() == 1) {//被拉黑的关注时状态还是被拉黑
                                    FriendDao.getInstance().updateBeBlack(mLoginUserId, user.getUserId(), 1);
                                    FriendDao.getInstance().updateFriendStatus(mLoginUserId, user.getUserId(), Friend.STATUS_ATTENTION);
                                } else {
                                    FriendDao.getInstance().updateBeBlack(mLoginUserId, user.getUserId(), 0);
                                    FriendDao.getInstance().updateFriendStatus(mLoginUserId, user.getUserId(), Friend.STATUS_ATTENTION);
                                }

                                user.getFriends().setStatus(Friend.STATUS_ATTENTION);
                                mAdapter.notifyDataSetChanged();
                                ToastUtil.showToast(getContext(), "关注对方成功");

                            } else if (result.getData().getType() == 2 || result.getData().getType() == 4) {// 已经是好友了
                                if (user.getFriends() == null ||
                                        (user.getFriends().getReplyStatus() != Friend.STATUS_REPLAY_BOTH
                                                && user.getFriends().getIsBeenBlack() != 0
                                                && result.getData().getIsFollowed() == 0)) {// 未回复并且未关注过的发送打招呼消息

                                    doSayHello(user, coreManager.getSelf().getNickName() + "关注了你，你们已经是好友，可以互发语音");
                                }
                                FriendDao.getInstance().updateFriendStatus(mLoginUserId, user.getUserId(), Friend.STATUS_FRIEND);
                                user.getFriends().setStatus(Friend.STATUS_FRIEND);
                                mAdapter.notifyDataSetChanged();
                            } else if (result.getData().getType() == 5) {
                                ToastUtil.showToast(getActivity(), R.string.add_attention_failed);
                            }
                        } else {
                            Toast.makeText(getActivity(), result.getResultMsg() + "", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        Toast.makeText(getActivity(), R.string.tip_hello_failed, Toast.LENGTH_SHORT).show();
                        ToastUtil.showErrorNet(getActivity());
                    }
                });
    }

    private void cancelAttention(User user) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("toUserId", user.getUserId());
        DialogHelper.showDefaulteMessageProgressDialog(getActivity());

        HttpUtils.get().url(coreManager.getConfig().CANEL_ATTENTION)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {

                    @Override
                    public void onResponse(ObjectResult<Void> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1) {
                            ToastUtil.showToast(getActivity(), result.getResultMsg());

                            //好友取消关注需要在关系通知提醒
                            if (user.getFriends() != null && user.getFriends().getStatus() == Friend.STATUS_FRIEND) {
                                ChatMessage removeChatMessage = new ChatMessage();
                                removeChatMessage.setContent("你取关了" + user.getNickName() + "，解除好友关系");
                                removeChatMessage.setTimeSend(TimeUtils.sk_time_current_time());
                                FriendDao.getInstance().updateLastChatMessage(mLoginUserId, Friend.ID_NEW_FRIEND_MESSAGE, removeChatMessage);

                                NewFriendMessage message = NewFriendMessage.createWillSendMessage(
                                        coreManager.getSelf(), XmppMessage.TYPE_CANCEL_ATTENTION, null, user);

                                NewFriendDao.getInstance().createOrUpdateNewFriend(message);
                                NewFriendDao.getInstance().changeNewFriendState(message.getUserId(), Friend.STATUS_27);
                                ListenerManager.getInstance().notifyNewFriend(mLoginUserId, message, true);

                                CardcastUiUpdateUtil.broadcastUpdateUi(getActivity());
                                user.getFriends().setStatus(Friend.STATUS_BE_ATTENTION);
                                mAdapter.notifyDataSetChanged();
                            } else {

                                if (user.getFriends().getIsBeenBlack() == 1) {//被拉黑的关注时状态还是被拉黑
                                    FriendDao.getInstance().updateBeBlack(mLoginUserId, user.getUserId(), 1);
                                    FriendDao.getInstance().updateFriendStatus(mLoginUserId, user.getUserId(), Friend.STATUS_UNKNOW);
                                } else {
                                    FriendDao.getInstance().updateFriendStatus(mLoginUserId, user.getUserId(), Friend.STATUS_UNKNOW);
                                    FriendDao.getInstance().updateBeBlack(mLoginUserId, user.getUserId(), 0);
                                }

                                user.getFriends().setStatus(Friend.STATUS_UNKNOW);
                                mAdapter.notifyDataSetChanged();
                            }
                        } else {
                            ToastUtil.showToast(getActivity(), result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                    }
                });
    }

    private void showCancelAttentionDialog(User user) {

        SelectionFrame mSF = new SelectionFrame(getActivity());
        mSF.setSomething(getString(R.string.dialog_title), getString(R.string.sure_cancel_attention), new SelectionFrame.OnSelectionFrameClickListener() {
            @Override
            public void cancelClick() {
            }

            @Override
            public void confirmClick() {
                cancelAttention(user);
            }
        });
        mSF.show();
    }

    // 打招呼
    private void doSayHello(User user, String text) {
        ChatMessage sayMessage = new ChatMessage();
        sayMessage.setFromUserId(mLoginUserId);
        sayMessage.setFromUserName(coreManager.getSelf().getNickName());
        sayMessage.setToUserId(user.getUserId());
        sayMessage.setContent(text);
        sayMessage.setType(XmppMessage.TYPE_TEXT); //文本类型
        sayMessage.setMsgType(ChatMessage.TYPE_HELLO);
        sayMessage.setMySend(true);
        sayMessage.setMessageState(ChatMessageListener.MESSAGE_SEND_SUCCESS);
        sayMessage.setPacketId(UUID.randomUUID().toString().replaceAll("-", ""));
        sayMessage.setTimeSend(TimeUtils.sk_time_current_time());

        // 这里最终调用smack的发送消息，

        coreManager.sendChatMessage(user.getUserId(), sayMessage);
        ChatMessageDao.getInstance().saveNewSingleChatMessage(mLoginUserId, user.getUserId(), sayMessage);


    }

}
